<template>
  <div>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :immediate-check="false"
      offset="50"
      @load="onLoad"
    >

    <!--  在组件标签中，会把事件修饰符后面的事件修饰成子向父传参的自定义事件
    解决：1.在事件后面添加.native 修饰符，告诉vue这是个原生事件
         2. 在子组件created钩子中，用$emit（‘click’） 来监听事件，名字与该事件名字一致 -->
      <article-item
      v-for="item in articleList"
      :key="item.art_id"
      :obj="item"
      @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
      />
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import { timeAgo } from '@/utils/date.js'
import { getArticlesListApi } from '@/api'
import ArticleItem from './components/ArticleItem.vue'

export default {
  components: { ArticleItem },
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      nextTime: null,
      refreshing: false
    }
  },
  props: {
    cid: Number
  },
  async created () {
    this.getArticlesList()
  },
  methods: {
    onRefresh () {
      // 刷新之后将时间戳清除，获取最新时间
      this.nextTime = null
      // 将数据清空重新获取并渲染
      this.articleList = []
      this.getArticlesList()
      // 将刷新状态重置
      this.refreshing = false
    },
    onLoad () {
      // 解决刚进入页面，会请求两次数据的问题
      // 当created钩子请求后获得数据，再次下拉才会请求数据
      // if (this.articleList.length > 0) {
      this.getArticlesList()
      // }
      console.log(1)
    },
    async getArticlesList () {
      const res = await getArticlesListApi({
        channelid: this.cid,
        timestamp: this.nextTime
      })
      // console.log(res)
      res.data.data.results.forEach((item) => {
        item.pubdate = timeAgo(item.pubdate)
      })
      if (res.data.data.results.length === 0) {
        this.loading = false
        this.finished = true
      } else {
        this.nextTime = res.data.data.pre_timestamp
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
